// IPFS配置验证脚本
// 验证您的IPFS hash和元数据配置

const fs = require('fs');
const path = require('path');

// 您的IPFS配置
const IPFS_CONFIG = {
    folderHash: "QmYP7zPrdxLPeJ4h3YghxYZ7YYn3dYjF1R25TxfG9cG3jn",
    baseURI: "ipfs://QmYP7zPrdxLPeJ4h3YghxYZ7YYn3dYjF1R25TxfG9cG3jn/",
    nftFiles: [
        "myNFT1.jpeg",
        "myNFT2.jpeg",
        "myNFT3.jpeg",
        "myNFT4.jpeg",
        "myNFT5.jpeg"
    ]
};

// 验证IPFS配置
function verifyIPFSConfig() {
    console.log("🔍 验证IPFS配置...\n");

    // 1. 验证hash格式
    console.log("1️⃣ 验证IPFS Hash格式:");
    const hashPattern = /^Qm[1-9A-HJ-NP-Za-km-z]{44}$/;
    if (hashPattern.test(IPFS_CONFIG.folderHash)) {
        console.log("✅ IPFS Hash格式正确:", IPFS_CONFIG.folderHash);
    } else {
        console.log("❌ IPFS Hash格式错误:", IPFS_CONFIG.folderHash);
    }

    // 2. 验证baseURI格式
    console.log("\n2️⃣ 验证BaseURI格式:");
    const expectedBaseURI = `ipfs://${IPFS_CONFIG.folderHash}/`;
    if (IPFS_CONFIG.baseURI === expectedBaseURI) {
        console.log("✅ BaseURI格式正确:", IPFS_CONFIG.baseURI);
    } else {
        console.log("❌ BaseURI格式错误:");
        console.log("   当前:", IPFS_CONFIG.baseURI);
        console.log("   期望:", expectedBaseURI);
    }

    // 3. 验证文件列表
    console.log("\n3️⃣ 验证NFT文件列表:");
    IPFS_CONFIG.nftFiles.forEach((fileName, index) => {
        console.log(`   ${index + 1}. ${fileName}`);
    });

    // 4. 生成访问URL
    console.log("\n4️⃣ 生成访问URL:");
    console.log("📁 IPFS文件夹:");
    console.log(`   https://ipfs.io/ipfs/${IPFS_CONFIG.folderHash}/`);

    console.log("\n🖼️  NFT图片文件:");
    IPFS_CONFIG.nftFiles.forEach((fileName, index) => {
        const fileURL = `https://ipfs.io/ipfs/${IPFS_CONFIG.folderHash}/${fileName}`;
        console.log(`   ${index + 1}. ${fileName}: ${fileURL}`);
    });

    // 5. 生成铸造URI
    console.log("\n5️⃣ 生成铸造URI:");
    IPFS_CONFIG.nftFiles.forEach((fileName, index) => {
        const tokenURI = `${IPFS_CONFIG.baseURI}${fileName}`;
        console.log(`   Token ${index + 1}: ${tokenURI}`);
    });
}

// 验证元数据JSON文件
function verifyMetadataJSON() {
    console.log("\n\n🔍 验证元数据JSON文件...\n");

    const metadataPath = path.join(__dirname, 'IPFS', 'myNFTMetadata.json');

    try {
        if (fs.existsSync(metadataPath)) {
            const metadataContent = fs.readFileSync(metadataPath, 'utf8');
            const metadata = JSON.parse(metadataContent);

            console.log("✅ 元数据JSON文件存在且格式正确");
            console.log(`📊 包含 ${metadata.length} 个NFT的元数据`);

            // 验证每个NFT的元数据
            metadata.forEach((nft, index) => {
                console.log(`\n🎨 NFT ${index + 1}:`);
                console.log(`   - 名称: ${nft.name}`);
                console.log(`   - 描述: ${nft.description}`);
                console.log(`   - 图片: ${nft.image}`);

                // 验证图片URL格式
                const expectedImageURL = `ipfs://${IPFS_CONFIG.folderHash}/${IPFS_CONFIG.nftFiles[index]}`;
                if (nft.image === expectedImageURL) {
                    console.log("   ✅ 图片URL正确");
                } else {
                    console.log("   ❌ 图片URL错误:");
                    console.log(`      当前: ${nft.image}`);
                    console.log(`      期望: ${expectedImageURL}`);
                }
            });

        } else {
            console.log("❌ 元数据JSON文件不存在:", metadataPath);
        }
    } catch (error) {
        console.log("❌ 读取元数据JSON文件失败:", error.message);
    }
}

// 生成部署配置
function generateDeployConfig() {
    console.log("\n\n🚀 生成部署配置...\n");

    const deployConfig = {
        name: "MyLearningNFT",
        symbol: "MLN",
        baseURI: IPFS_CONFIG.baseURI,
        maxSupply: 1000,
        maxMintPerAddress: 10,
        ipfsConfig: IPFS_CONFIG
    };

    console.log("📋 部署配置:");
    console.log(JSON.stringify(deployConfig, null, 2));

    // 保存配置到文件
    const configPath = path.join(__dirname, 'deploy-config.json');
    fs.writeFileSync(configPath, JSON.stringify(deployConfig, null, 2));
    console.log(`\n💾 配置已保存到: ${configPath}`);
}

// 生成铸造脚本
function generateMintScript() {
    console.log("\n\n🎨 生成铸造脚本...\n");

    const mintScript = `
// 基于您的IPFS配置的铸造脚本
const { ethers } = require('ethers');

const CONTRACT_ADDRESS = "YOUR_CONTRACT_ADDRESS"; // 部署后替换
const CONTRACT_ABI = [/* 您的合约ABI */];

async function mintAllNFTs() {
    const provider = new ethers.providers.JsonRpcProvider(process.env.SEPOLIA_RPC_URL);
    const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
    const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, wallet);
    
    const nftFiles = [
        "myNFT1.jpeg",
        "myNFT2.jpeg", 
        "myNFT3.jpeg",
        "myNFT4.jpeg",
        "myNFT5.jpeg"
    ];
    
    for (let i = 0; i < nftFiles.length; i++) {
        const fileName = nftFiles[i];
        console.log(\`铸造NFT \${i + 1}: \${fileName}\`);
        
        try {
            const tx = await contract.mintNFT(wallet.address, fileName);
            const receipt = await tx.wait();
            
            const mintEvent = receipt.events?.find(e => e.event === 'NFTMinted');
            const tokenId = mintEvent?.args?.tokenId;
            
            console.log(\`✅ 铸造成功，Token ID: \${tokenId}\`);
            
            // 验证URI
            const tokenURI = await contract.tokenURI(tokenId);
            console.log(\`   URI: \${tokenURI}\`);
            
        } catch (error) {
            console.log(\`❌ 铸造失败: \${error.message}\`);
        }
    }
}

mintAllNFTs().catch(console.error);
`;

    const scriptPath = path.join(__dirname, 'mint-nfts.js');
    fs.writeFileSync(scriptPath, mintScript);
    console.log(`💾 铸造脚本已保存到: ${scriptPath}`);
}

// 主函数
function main() {
    console.log("🎯 IPFS配置验证工具");
    console.log("=" * 50);

    verifyIPFSConfig();
    verifyMetadataJSON();
    generateDeployConfig();
    generateMintScript();

    console.log("\n\n✅ 验证完成！");
    console.log("\n💡 下一步:");
    console.log("1. 检查生成的访问URL是否可访问");
    console.log("2. 使用生成的配置部署合约");
    console.log("3. 使用生成的脚本铸造NFT");
}

// 运行验证
main();
